//
//  XASectionPageLayout.Swift
//  XAPageViewDemo
//
//  Created by XangAm on 2018/1/4.
//  Copyright © 2018年 Lan. All rights reserved.
//

import UIKit

class XASectionPageLayout: UICollectionViewFlowLayout {
    internal  var cols : Int   = 0
    internal  var rows : Int   = 0
    fileprivate var totalPageCount  = 0
    fileprivate var attrs  = [UICollectionViewLayoutAttributes]()
    
    
    override func prepare() {
        super.prepare()
        guard let collectionView = collectionView else {
            return
        }
        
        let collectionViewW = collectionView.bounds.width,collectionViewH = collectionView.bounds.height
        let sections =  collectionView.numberOfSections
        for sectionIndex in 0..<sections{
            let items = collectionView.numberOfItems(inSection: sectionIndex)
            var sectionPageIndex = 0;
            for itemIndex in 0..<items{
                let indexPath = IndexPath(item: itemIndex, section: sectionIndex)
                let attr  = UICollectionViewLayoutAttributes(forCellWith: indexPath)
                sectionPageIndex = itemIndex / (cols * rows)
                let currentPageIndex = sectionPageIndex + totalPageCount
                let rowIndex  = (itemIndex - sectionPageIndex * (cols * rows)) / cols
                let colIndex  = (itemIndex - sectionPageIndex * (cols * rows)) % cols
                //计算Frame
                let width  = (collectionViewW - sectionInset.left - sectionInset.right - (CGFloat((cols - 1)) * minimumInteritemSpacing)) / CGFloat(cols)
                let height = (collectionViewH - sectionInset.top - sectionInset.bottom - (CGFloat((rows - 1)) * minimumInteritemSpacing)) / CGFloat(rows)
                let x = (CGFloat(currentPageIndex) * collectionViewW) + sectionInset.left + CGFloat(colIndex) * (width + minimumInteritemSpacing)
                let y = sectionInset.top + CGFloat(rowIndex) * (height + minimumLineSpacing)
                
                attr.frame = CGRect(x: x, y: y, width: width, height: height)
                attrs.append(attr)
            }
            totalPageCount += sectionPageIndex + 1
            
        }
        
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        
        return attrs
    }
    
    override var collectionViewContentSize: CGSize{
        
        return CGSize(width: CGFloat(totalPageCount) * (collectionView?.bounds.width ?? 0), height: 0)
        
    }
    
}
